package com.boge.study.excel;

import com.google.common.collect.Lists;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class CSVUtils {

    public static void main(String[] args) {
        List exportData = Lists.newArrayList();
        Map row1 = new LinkedHashMap<String, String>();
        row1.put("1", "11");
        row1.put("2", "");
        row1.put("3", "13");
        row1.put("4", "14");
        exportData.add(row1);

        row1 = new LinkedHashMap<String, String>();
        row1.put("1", "21");
        row1.put("2", "22");
        row1.put("3", "23");
        row1.put("4", "24");
        exportData.add(row1);

        LinkedHashMap map = new LinkedHashMap();
        map.put("1", "第一列");
        map.put("2", "第二列");
        map.put("3", "第三列");
        map.put("4", "第四列");

        String path = "d:/export/";
        String fileName = "csv文件导出";
        File file = CSVUtils.createCSVFile(exportData, map, path, fileName);
        String fileName2 = file.getName();
        System.out.println("文件名称：" + fileName2);

    }

    /**
     * 生成CSV文件
     *
     * @param exportData
     * @param map
     * @param outPutPath
     * @param fileName
     * @return
     */
    public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath, String fileName) {
        File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            File file = new File(outPutPath);
            if (!file.exists()) {
                file.mkdir();
            }
            //定义文件名格式并创建
            csvFile = new File(outPutPath + fileName + ".csv");
            //UTF-8使得正确读取分隔符“,”
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GBK"), 1024);
            System.out.println("csvFileOutputStream:" + csvFileOutputStream);

            //写入文件头部
            for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext(); ) {
                Map.Entry<String, String> propertyEntry = (Map.Entry) propertyIterator.next();
                csvFileOutputStream.write(propertyEntry.getValue() != null ?
                        new String((propertyEntry.getValue()).getBytes("GBK"), "GBK") : "");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
                System.out.println(new String((propertyEntry.getValue()).getBytes("GBK"), "GBK"));
            }
            csvFileOutputStream.write("\r\n");

            // 写入文件内容
            for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
                Object row = (Object) iterator.next();
                for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
                        .hasNext();) {
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
                            .next();
                    csvFileOutputStream.write((String) BeanUtils.getProperty(row,
                            ((String) propertyEntry.getKey()) != null? (String) propertyEntry.getKey()
                                    : ""));
                    if (propertyIterator.hasNext()) {
                        csvFileOutputStream.write(",");
                    }
                }
                if (iterator.hasNext()) {
                    csvFileOutputStream.write("\r\n");
                }
            }
            csvFileOutputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return csvFile;
    }

    /**
     * 下载文件
     *
     * @param response
     * @param csvFilePath
     * @param fileName
     */
    public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName) {
        response.setContentType("application/csv;charset=GBK");
        InputStream in = null;
        try {
            response.setHeader("Content-Disposition", "attachment; fileName=" +
                    new String(fileName.getBytes("GBK"), "ISO8859-1"));

            in = new FileInputStream(csvFilePath);
            int len = 0;
            byte[] buffers = new byte[1024];
            response.setCharacterEncoding("GBK");
            OutputStream out = response.getOutputStream();
            while ((len = in.read(buffers)) > 0) {
                out.write(buffers, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除该目录filePath下的所有文件
     *
     * @param filePath
     */
    public static void deleteFiles(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i ++) {
                if (files[i].isFile()) {
                    files[i].delete();
                }
            }
        }
    }

    /**
     * 删除单个文件
     * @param filePath
     * @param fileName
     */
    public static void deleteFile(String filePath, String fileName) {
        File file = new File(filePath);
        if (file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i ++) {
                if (files[i].isFile()) {
                    if (files[i].getName().equals(fileName)) {
                        files[i].delete();
                        return;
                    }

                }
            }
        }
    }

}
